﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Users;
using iOak.Business.Campaigns;
using iOak.Domain.Campaigns;
using iOak.Common.Untity;
using iOak.Common;
using System.Collections;
using System.Transactions;
using iOak.Web.ExeclHelper;
using System.Web.UI.HtmlControls;

namespace iOak.Web.Administration
{
    public partial class CampaignList : BasePage
    {
        private WorkAssistant _workassistant = new WorkAssistant();
        private CampaignService _campaignService = new CampaignService();
        private ApplicationService _applicationService = new ApplicationService();
        private ApplicationCandidateService _applicationCandidateService = new ApplicationCandidateService();

        #region 页面事件
        /// <summary>
        /// 页面初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            pagerControl.PageIndexChange += new Modules.PagerControl.OnPageIndexChangeHandler(pagerControl_PageIndexChange);
            if (!Page.IsPostBack)
            {
                IniStatusList();
                //IniUserList();
                BindCampaignList();
            }
        }

        protected void pagerControl_PageIndexChange(object serder, EventArgs e)
        {
            BindCampaignList();
        }

        /// <summary>
        /// gvCampaign行绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvCampaign_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Campaign campaign = e.Row.DataItem as Campaign;
                Label lblReceiveCount = e.Row.FindControl("lblReceiveCount") as Label;
                //总申请书个数
                int applicationCount = _applicationService.GetCountByCampaignId(campaign.CampaignId);
                //未申报的申请书个数
                int openCount = _applicationService.GetCountByCampaignId(campaign.CampaignId, ApplicationStatus.Open);
                //收到的个数
                lblReceiveCount.Text = (applicationCount - openCount).ToString();
                Label lblCandidateCount = e.Row.FindControl("lblCandidateCount") as Label;
                lblCandidateCount.Text = _applicationCandidateService.GetCount(campaign.CampaignId, includeOpen: false).ToString();
                Label lblMeetCount = e.Row.FindControl("lblMeetCount") as Label;
                lblMeetCount.Text = _applicationCandidateService.GetCount(campaignId: campaign.CampaignId, passed: true).ToString();
                Label lblStatus = e.Row.FindControl("lblStatus") as Label;
                lblStatus.Text = ResourceHelper.GetCampaignStatusName(campaign.Status);
                //设置操作按钮
                Panel phOpenMenu = e.Row.FindControl("pnlOptionMenu") as Panel;
                SetOptionMenu(campaign.Status, phOpenMenu);
                if (campaign.Status == (int)CampaignStatus.Appling)
                {
                    Panel pnlOptionMenu = e.Row.FindControl("pnlOptionMenu") as Panel;
                    PlaceHolder phClose = pnlOptionMenu.FindControl("phClose") as PlaceHolder;
                    HtmlGenericControl divClose = pnlOptionMenu.FindControl("divClose") as HtmlGenericControl;
                    //存在处于Submitted状态的申请
                    bool existSubmitted = _applicationService.GetCountByCampaignId(campaign.CampaignId, ApplicationStatus.Submitted) != 0;
                    divClose.Attributes.Add("onclick", String.Format("$('.optionMenu').hide();closeClick('{0}',{1})", campaign.CampaignId.ToString(), existSubmitted.ToString().ToLower()));
                }
            }
        }

        /// <summary>
        /// 检索按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFind_Click(object sender, EventArgs e)
        {
            gvCampaign.PageIndex = 0;
            BindCampaignList();
        }

        protected void btnPostBack_Click(object sender, EventArgs e)
        {
            Guid id;
            switch (hidEventName.Value)
            {
                case "delete":
                    id = Guid.Parse(hidEventArguments.Value);
                    DeleteCampaign(id);
                    break;
                case "open":
                    id = Guid.Parse(hidEventArguments.Value);
                    OpenCampaign(id);
                    break;
                //case "checking":
                //    id = Guid.Parse(hidEventArguments.Value);
                //    CheckingCampaign(id);
                //    break;
                case "assign":
                    id = Guid.Parse(hidEventArguments.Value.Split('|')[0]);
                    AssignCampaign(id, hidEventArguments.Value.Split('|')[1].Split(','));
                    break;
                case "close":
                    id = Guid.Parse(hidEventArguments.Value);
                    CloseCampaign(id);
                    break;
                case "export":
                    id = Guid.Parse(hidEventArguments.Value);
                    CSVHelper.WriteCSV(id);
                    break;

            }
        }
        #endregion

        #region 处理函数
        /// <summary>
        /// 绑定Campaign列表
        /// </summary>
        private void BindCampaignList()
        {
            DateTime tempDate;
            DateTime? startDate = null;
            if (!String.IsNullOrWhiteSpace(txtStartDate.Text))
            {
                if (DateTime.TryParse(txtStartDate.Text, out tempDate))
                {
                    startDate = tempDate;
                }
                else
                {
                    txtStartDate.Text = String.Empty;
                }
            }
            DateTime? endDate = null;
            if (!String.IsNullOrWhiteSpace(txtEndDate.Text))
            {
                if (DateTime.TryParse(txtEndDate.Text, out tempDate))
                {
                    endDate = tempDate;
                }
                else
                {
                    txtEndDate.Text = String.Empty;
                }
            }
            int? status = null;
            if (ddlStatus.SelectedIndex != 0)
            {
                status = int.Parse(ddlStatus.SelectedValue);
            }

            CampaignService campaignService = new CampaignService();
            //检索符合条件的campaign
            List<Campaign> campaignList = campaignService.FindCampaigns(txtSubject.Text, startDate, endDate, status);
            pagerControl.BindData(gvCampaign, campaignList.OrderByDescending(item => item.StartDate).ToList());
        }

        private void DeleteCampaign(Guid id)
        {
            CampaignService campaignService = new CampaignService();
            campaignService.Delete(id);
            BindCampaignList();
        }

        private void OpenCampaign(Guid id)
        {
            CampaignService campaignService = new CampaignService();
            var campaign = campaignService.Retrieve(id);
            campaign.Status = (int)CampaignStatus.Appling;
            campaign.ModifiedOn = DateTime.Now;
            campaign.ModifiedBy = _workassistant.CurrentUser.UserId;
            campaignService.Update(campaign);
            BindCampaignList();
        }

        //private void CheckingCampaign(Guid id)
        //{
        //    CampaignService campaignService = new CampaignService();
        //    ApplicationService applicationService = new ApplicationService();
        //    var campaign = campaignService.Retrieve(id);
        //    var applicationList = applicationService.GetListByCampaignId(campaign.CampaignId);
        //    using (TransactionScope ts = new TransactionScope())
        //    {
        //        campaign.Status = (int)CampaignStatus.Checking;
        //        campaign.ModifiedOn = DateTime.Now;
        //        campaign.ModifiedBy = _workassistant.CurrentUser.UserId; ;
        //        campaignService.Update(campaign);
        //        foreach (var application in applicationList)
        //        {
        //            //将处于已申报状态的申请书修改为审核中状态
        //            if (application.Status == (int)ApplicationStatus.Submitted)
        //            {
        //                application.Status = (int)ApplicationStatus.Checking;
        //                applicationService.Update(application);
        //            }
        //        }
        //        ts.Complete();
        //    }
        //    BindCampaignList();
        //}

        private void CloseCampaign(Guid id)
        {
            //ApplicationService applicationService = new ApplicationService();
            //int applicationCount = applicationService.GetCountByCampaignId(id);
            ////已审核的申请书个数
            //int checkedCount = applicationService.GetCountByCampaignId(id, ApplicationStatus.Checked);
            ////未申报的申请书个数
            //int openCount = applicationService.GetCountByCampaignId(id, ApplicationStatus.Open);
            ////如果Campaign下的所有申请书只处于已经审核或未申报状态，则改变Campaign的状态
            //if (applicationCount == (checkedCount + openCount))
            //{
            CampaignService campaignService = new CampaignService();
            Campaign campaign = campaignService.Retrieve(id);
            campaign.Status = (int)CampaignStatus.Closed;
            campaign.ModifiedBy = _workassistant.CurrentUser.UserId;
            campaign.ModifiedOn = DateTime.Now;
            campaignService.Update(campaign);
            BindCampaignList();
            //}
            //else 
            //{
            //    ClientScript.RegisterStartupScript(typeof(Page), "showWarnning", "$(document).ready(function(){jAlert('该人才申报的申请书尚未审核结束！');});", true);
            //}
        }

        /// <summary>
        /// 初始化人员列表
        /// </summary>
        private void IniUserList()
        {
            UserService userService = new UserService();
            chklUserList.DataSource = userService.GetListByCompanyId(_workassistant.CurrentUser.CompanyId);
            chklUserList.DataTextField = "FullName";
            chklUserList.DataValueField = "UserId";
            chklUserList.DataBind();
            foreach (ListItem checkBox in chklUserList.Items)
            {
                checkBox.Selected = true;
            }
        }

        /// <summary>
        /// 初始化状态列表
        /// </summary>
        private void IniStatusList()
        {
            int openStatus = (int)CampaignStatus.Open;
            int applingStatus = (int)CampaignStatus.Appling;
            //int checkingStatus = (int)CampaignStatus.Checking;
            int closedStatus = (int)CampaignStatus.Closed;
            ddlStatus.Items.Add(new ListItem("", ""));
            ddlStatus.Items.Add(new ListItem(ResourceHelper.GetCampaignStatusName(openStatus), openStatus.ToString()));
            ddlStatus.Items.Add(new ListItem(ResourceHelper.GetCampaignStatusName(applingStatus), applingStatus.ToString()));
            //ddlStatus.Items.Add(new ListItem(ResourceHelper.GetCampaignStatusName(checkingStatus), checkingStatus.ToString()));
            ddlStatus.Items.Add(new ListItem(ResourceHelper.GetCampaignStatusName(closedStatus), closedStatus.ToString()));
        }

        private void AssignCampaign(Guid id, String[] userIdList)
        {
            Dictionary<Guid, int> htUserIdList = new Dictionary<Guid, int>();
            for (int i = 0; i < userIdList.Length; i++)
            {
                if (!String.IsNullOrWhiteSpace(userIdList[i]))
                {
                    htUserIdList.Add(Guid.Parse(userIdList[i]), 0);
                }
            }
            //获取所选Campaign下的申请书集合
            ApplicationService applicationService = new ApplicationService();
            ApplicationCandidateService applicationCandidateService = new ApplicationCandidateService();
            List<ApplicationBase> applicationList = applicationService.GetListByCampaignId(id);
            foreach (var application in applicationList)
            {
                //取得被分配到的数量最少的人员
                int minCount = htUserIdList.Min(item => item.Value);
                var userInfo = htUserIdList.First(item => item.Value == minCount);
                //获取候选人集合
                List<ApplicationCandidate> applicationCandidateList = applicationCandidateService.GetListByApplicationId(application.ApplicationId);
                foreach (var applicationCandidate in applicationCandidateList)
                {
                    //如果未输入过审核结果
                    if (applicationCandidate.Passed == null)
                    {
                        applicationCandidate.CheckedBy = userInfo.Key;
                        //applicationCandidate.CheckerOn = DateTime.Now;
                        applicationCandidateService.Update(applicationCandidate);
                    }
                }
                htUserIdList[userInfo.Key]++;
            }
        }

        /// <summary>
        /// 设定操作菜单
        /// </summary>
        /// <param name="status">Campaign状态</param>
        /// <param name="phOpenMenu">菜单容器</param>
        private void SetOptionMenu(int status, Panel pnlOptionMenu)
        {

            PlaceHolder phModify = pnlOptionMenu.FindControl("phModify") as PlaceHolder;
            PlaceHolder phDelete = pnlOptionMenu.FindControl("phDelete") as PlaceHolder;
            PlaceHolder phPreview = pnlOptionMenu.FindControl("phPreview") as PlaceHolder;
            PlaceHolder phOpen = pnlOptionMenu.FindControl("phOpen") as PlaceHolder;
            PlaceHolder phChecking = pnlOptionMenu.FindControl("phChecking") as PlaceHolder;
            //PlaceHolder phAssign = pnlOptionMenu.FindControl("phAssign") as PlaceHolder;
            PlaceHolder phClose = pnlOptionMenu.FindControl("phClose") as PlaceHolder;
            PlaceHolder phExport = pnlOptionMenu.FindControl("phExport") as PlaceHolder;
            Label lblPreview = phPreview.FindControl("lblPreview") as Label;
            switch (status)
            {
                case (int)CampaignStatus.Open:
                    phChecking.Visible = false;
                    //phAssign.Visible = false;
                    phPreview.Visible = false;
                    phClose.Visible = false;
                    phExport.Visible = false;
                    break;
                case (int)CampaignStatus.Appling:
                    phOpen.Visible = false;
                    phModify.Visible = false;
                    phDelete.Visible = false;
                    phClose.Visible = false;
                    //phAssign.Visible = false;
                    phClose.Visible = false;
                    //phExport.Visible = false;
                    break;
                //case (int)CampaignStatus.Checking:
                //    lblPreview.Text = "浏览申请书";
                //    phOpen.Visible = false;
                //    phModify.Visible = false;
                //    phDelete.Visible = false;
                //    phChecking.Visible = false;
                //    break;
                case (int)CampaignStatus.Closed:
                    lblPreview.Text = "浏览申请书";
                    phOpen.Visible = false;
                    phModify.Visible = false;
                    phDelete.Visible = false;
                    phChecking.Visible = false;
                    //phAssign.Visible = false;
                    phClose.Visible = false;
                    break;
            }
        }
        #endregion

        protected void buttonExport_Click(object sender, EventArgs e)
        {
            CSVHelper.ExportAllCSV();
        }
    }
}